/*Jeff Finn
 * CSC 342
 * Adv Database Spring 2014
 * Team 4
 */

package controller;

import java.sql.SQLException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public final class ErrorHandle {
	
	private final static boolean writetoconsole = true;
	private final static boolean writetologfile = false;
	private final static String Filepath = "./T4Error.log";
	
	private final static BufferedWriter GetLogFile()
	{
		File file = new File(Filepath);
		FileWriter fw = null;
		BufferedWriter bw = null;
		
		try
		{
			if (!file.exists()) {
				file.createNewFile();
		}

			fw = new FileWriter(file.getAbsoluteFile());
			bw = new BufferedWriter(fw);
		}
		catch(Exception e)
		{
			System.out.println("Log File Writer Could Not Be Established");
		}

		return bw;
	}
	
	public static void LogError(Exception e, String Message)
	{
		if(writetoconsole)
			System.out.println(Message);
		if(writetologfile)
		{
			try
			{
				GetLogFile().write(Message);
			}
			catch(Exception io)
			{
				System.out.println("Log File Cannot be written to");
			}
		}
		LogError(e);
	}
	public static void LogError(Exception e)
	{
		if(writetoconsole)
		{
			System.out.println("/nMessage: " + e.getMessage());
			e.printStackTrace();
		}
		if(writetologfile)
		{
			try
			{
				
				StackTraceElement[] steArray = e.getStackTrace();
				for (StackTraceElement ste : steArray)
				{
					GetLogFile().write("/nMessage: " + ste.toString());
				}
			}
			catch(Exception io)
			{
				System.out.println("Log File Cannot be written to");
			}
		}
	}
	
	public static void LogError(SQLException e, String Message)
	{
		if(writetoconsole)
			System.out.println(Message);
		if(writetologfile)
		{
			try
			{
				GetLogFile().write(Message);
			}
			catch(Exception io)
			{
				System.out.println("Log File Cannot be written to");
			}
		}
		LogError(e);
	}
	public static void LogError(SQLException e)
	{
		if(writetoconsole)
		{
			System.out.println("/nState: " + e.getSQLState());
			System.out.println("/nMessage: " + e.getMessage());
			e.printStackTrace();
		}
		try
		{
			GetLogFile().write("/nState" + e.getSQLState());
			StackTraceElement[] steArray = e.getStackTrace();
			for (StackTraceElement ste : steArray)
			{
				GetLogFile().write("/nMessage" + ste.toString());
			}
		}
		catch(Exception io)
		{
			System.out.println("Log File Cannot be written to");
		}
	}
}
